<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace Hyperf\RpcClient\Proxy;

use PhpParser\Node;
use PhpParser\Node\Stmt\Interface_;
use PhpParser\NodeVisitorAbstract;

class ProxyCallVisitor extends NodeVisitorAbstract
{
    /**
     * @var string
     */
    private $classname;

    public function __construct(string $classname)
    {
        $this->classname = $classname;
    }

    public function leaveNode(Node $node)
    {
        if ($node instanceof Interface_) {
            return new Node\Stmt\Class_($this->classname, [
                'stmts' => $node->stmts,
                'extends' => new Node\Name\FullyQualified(AbstractProxyService::class),
                'implements' => [
                    $node->name,
                ],
            ]);
        }
        if ($node instanceof Node\Stmt\ClassMethod) {
            $node->stmts = [
                new Node\Stmt\Return_(new Node\Expr\MethodCall(
                    new Node\Expr\PropertyFetch(new Node\Expr\Variable('this'), new Node\Identifier('client')),
                    new Node\Identifier('__call'),
                    [
                        new Node\Scalar\MagicConst\Function_(),
                        new Node\Expr\FuncCall(new Node\Name('func_get_args')),
                    ]
                )),
            ];
            return $node;
        }
        return parent::leaveNode($node); // TODO: Change the autogenerated stub
    }
}
